#!/usr/bin/env python
# coding=utf-8

from vavava import util
from datetime import datetime
from .. import fetcherbase, track_db

class FetcherAuspost(fetcherbase.FetcherBase):
    def __init__( self, item_id, log ):
        fetcherbase.FetcherBase.__init__(self, item_id=item_id, track_type=fetcherbase.TRACK_TYPE_AUSPOST,log=log)
        self.name = "FetcherAuspost|"+item_id
        self.fetch_url = r'http://auspost.com.au/track/track.html?id=%s' % self.item_id
        self.reg_str   = r'<tr[^>]*>\s*' \
                         r'<td[^>]*>\s*(?P<datetime>\d{2}/\d{2}/\d{2}\s*\d{2}:\d{2})\s*</td>\s*' \
                         r'<td[^>]*>(?P<desc>[^<]*)</td>\s*' \
                         r'<td[^>]*>(?P<location>[^<]*)</td>\s*' \
                         r'</tr>'
        self.charset   = r"ISO-8859-1"

    def _fetch(self):
        result_list = []
        html_data = self.http.Get(self.fetch_url)
        html = html_data.decode(self.charset)
        item_infos = util.reg_helper(html,self.reg_str)
        if len(item_infos) == 0:
            results = util.reg_helper(html,r'captcha\.html\?ts=(?P<random_id>[^"]*)')
            if len(results) > 0:
                self.log.error("[%s] need security code", self.name)
        for item_info in item_infos:
            item = track_db.TrackData.GetInstance(
                [
                    -1,
                    self.track_type,
                    self.item_id,
                    datetime.strptime(item_info[0], "%d/%m/%y %H:%M"),
                    item_info[1].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                    item_info[2].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                    -1,
                    None
                ]
            )
            if 'delivered' in item.description.lower():
                item.is_ended = 1
            result_list.append(item)

        self._chk_new_items(result_list)

